﻿using Abp;
using FwProject.Manager;
using FwProject.ShopApplication;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Abp.ObjectMapping;
using FwProject.ShoppingMall.EventAdvertising;
using Abp.Domain.Repositories;
using X.PagedList;
using System.Linq;
using AutoMapper.QueryableExtensions;
using FwProject.ShoppingMall.Com;
using FwProject.ShoppingMall.Shop;
using FwProject.Comm;
using Abp.AutoMapper;
using FwProject.Authorization.Users;
using FwProject.Shop.Dto;
using Abp.RemoteEventBus;
using Abp.BackgroundJobs;
using FwProject.BackGround.ShopProductShip;
using FwProject.BackGround;
using Abp.UI;
using FwProject.EventAdvertising.Dto;
using System.Globalization;
using FwProject.Pay;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using FwProject.ShopApplication.Configuration;
using Abp.Authorization;
using Microsoft.AspNetCore.Mvc;
using FwProject.ManagerNotification;
using FwProject.ManagerNotification.DataDto;

namespace FwProject.Com.Dto
{
    /// <summary>
    /// 购物车管理
    /// </summary>
    [AbpAuthorize]
    public class ShopOrderAppService : FwProjectAppServiceBase, IShopOrderAppService
    {
        private readonly ShopOrderManager _shopOrderManager;
        private readonly ShopUserCouponManager _shopUserCouponManager;
        private readonly ShopOrderCouponManager _shopOrderCouponManager;
        private readonly ShopOrderDetailsManager _shopOrderDetailsManager;
        private readonly IRepository<ShopOrder, Guid> _shopOrderRepository;
        private readonly IRepository<ShopProduct, Guid> _shopProductRepository;
        private readonly IRepository<ShopSecondkill, Guid> _shopSecondkillRepository;
        private readonly IRepository<ShopProductSku, Guid> _shopProductSkuRepository;
        private readonly IRepository<ShopOrderDetails, Guid> _shopOrderDetailsRepository;
        private readonly IRepository<SettlementSupplier, Guid> _settlementSupplierRepository;
        private readonly IRepository<ShopReceivingAddress, Guid> _repositoryShopReceivingAddress;
        private readonly IRepository<ShopCar, Guid> _shopCarrepository;
        private readonly IShopReceivingAddressAppService _shopReceivingAddressAppService;
        private readonly ShopUserCouponAppService _shopUserCouponAppService;
        private readonly IRepository<User, long> _repositoryUser;

        private readonly PublishNotifications _publishNotifications;

        private readonly IPayPayAppService _payPayAppService;
        private readonly IBackgroundJobManager _backgroundJobManager;
        public IRemoteEventBus remoteEventBus { get; set; }//缓存对象
        private Abp.IGuidGenerator _guid { get; set; }
        public IObjectMapper _map { get; set; }

        private readonly IHostingEnvironment _hostingEnvironment;

        private readonly IConfigurationRoot _appConfiguration;
        /// <summary>
        /// 构造注入函数
        /// </summary>
        /// <param name="shopOrderManager"></param>
        /// <param name="shopOrderRepository"></param>
        /// <param name="shopProductRepository"></param>
        /// <param name="shopSecondkillRepository"></param>
        /// <param name="shopProductSkuRepository"></param>
        /// <param name="shopUserCouponManager"></param>
        /// <param name="shopOrderCouponManager"></param>
        /// <param name="shopOrderDetailsRepository"></param>
        /// <param name="settlementSupplierRepository"></param>
        /// <param name="repositoryUser"></param>
        /// <param name="repositoryShopReceivingAddress"></param>
        /// <param name="shopOrderDetailsManager"></param>
        public ShopOrderAppService(ShopOrderManager shopOrderManager, IRepository<ShopOrder, Guid> shopOrderRepository, IRepository<ShopProduct, Guid> shopProductRepository,
            IRepository<ShopSecondkill, Guid> shopSecondkillRepository, IRepository<ShopProductSku, Guid> shopProductSkuRepository
            , ShopUserCouponManager shopUserCouponManager,
            ShopOrderCouponManager shopOrderCouponManager,
            IRepository<ShopOrderDetails, Guid> shopOrderDetailsRepository,
            IRepository<SettlementSupplier, Guid> settlementSupplierRepository,
            IRepository<User, long> repositoryUser,
            IRepository<ShopReceivingAddress, Guid> repositoryShopReceivingAddress,
            ShopOrderDetailsManager shopOrderDetailsManager,
            IBackgroundJobManager backgroundJobManager,
            IShopReceivingAddressAppService shopReceivingAddressAppService,
            IRepository<ShopCar, Guid> shopCarrepository,
            ShopUserCouponAppService shopUserCouponAppService,
            IPayPayAppService payPayAppService,
            IHostingEnvironment hostingEnvironment,
            PublishNotifications publishNotifications)
        {
            _hostingEnvironment = hostingEnvironment;
            _appConfiguration = _hostingEnvironment.GetAppConfiguration();
            _payPayAppService = payPayAppService;
            _shopUserCouponAppService = shopUserCouponAppService;
            _shopCarrepository = shopCarrepository;
            _shopReceivingAddressAppService = shopReceivingAddressAppService;
            remoteEventBus = NullRemoteEventBus.Instance;
            _shopOrderDetailsManager = shopOrderDetailsManager;
            _shopOrderCouponManager = shopOrderCouponManager;
            _shopUserCouponManager = shopUserCouponManager;
            _shopOrderManager = shopOrderManager;



            _guid = SequentialGuidGenerator.Instance;
            _map = NullObjectMapper.Instance;
            _shopOrderRepository = shopOrderRepository;
            _shopProductRepository = shopProductRepository;
            _shopSecondkillRepository = shopSecondkillRepository;
            _shopProductSkuRepository = shopProductSkuRepository;
            _shopOrderDetailsRepository = shopOrderDetailsRepository;
            _settlementSupplierRepository = settlementSupplierRepository;
            _repositoryUser = repositoryUser;
            _repositoryShopReceivingAddress = repositoryShopReceivingAddress;
            _backgroundJobManager = backgroundJobManager;
            _publishNotifications = publishNotifications;
        }

        #region 创建订单服务
        /// <summary>
        /// 创建一个订单
        /// </summary>
        /// <param name="Input">订单创建模型如果没有开启规格默认ShopskuId如果没有就传入00000000-0000-0000-0000-000000000000</param>
        /// <returns>PayData返回三个值 OrderNumber 支付的订单编号, PayTotal 总的支付金额  Id 订单主键</returns>
        public async Task<string> CreateShopOrder(ShopOrderInput Input)
        {
            if (Input.ReceivingAddress != Guid.Empty)
                new UserFriendlyException("请选择收货地址");

            if (Input.shopOrderDetailsInputList.Count > 0)
                new UserFriendlyException("请选择你要购买的商品");


            if (Input.PayType != PayType.微信支付 || Input.PayType != PayType.支付宝支付)
                new UserFriendlyException("支付方式不存在");


            var model = _map.Map<ShopOrder>(Input);
            string body = string.Empty;
            string subject = string.Empty;
            #region 用户确认订单
            if (AbpSession.UserId.HasValue)
            {
                model.Id = _guid.Create();
                model.UserId = AbpSession.UserId.Value;
                if (Input.ReceivingAddress == Guid.Empty)
                    throw new UserFriendlyException("请先选择一个收货地址！");

                //获取选择的收货地址，实际收货信息赋值;
                var receivingAddress = await _repositoryShopReceivingAddress.GetAsync(Input.ReceivingAddress);
                model.ActualReceivingAddress = $"{receivingAddress.AreaAddress} {receivingAddress.ReceivingAddress}";
                model.ActualReceivingName = receivingAddress.ReceivingName;
                model.ActualReceivingTel = receivingAddress.ReceivingTel;
                Random rand = new Random();
                int shu2 = RandomHelper.GetRandom(1000, 9999);
                model.OrderNumber = TimeHelp.OrderNumber(AbpSession.UserId.Value, shu2);

                ///订单明细计算
                List<ShopOrderDetails> list = new List<ShopOrderDetails>();
                foreach (var item in Input.shopOrderDetailsInputList)
                {
                    EnterOrderBySkillBuy(item.ShopproductId,item.ProductCount);
                    //订单明细生成
                    var Details = item.MapTo<ShopOrderDetails>();
                    Details.UserId = AbpSession.UserId.Value;
                    Details.Id = _guid.Create();
                    Details.OrderNumber = model.OrderNumber;
                    Details.ShopImagePic = _shopProductRepository.Get(Details.ShopproductId).ImagePic;
                    Details.OrderId = model.Id;
                    Details.PayPrice = ShopPrice(Details.ShopSkuId, Details.ShopproductId);///最终定位价格
                    Details.MarketPrice = ShopPrice(Details.ShopSkuId, Details.ShopproductId);///原始定位价格
                    Details.PayTotalPrice = Details.PayPrice * Details.ProductCount;//应支付
                    Details.PayAmountPrice = Details.PayTotalPrice;//实际应支付
                    Details.DiscountPrice = 0m;//优惠券支付

                    body += $"{Details.ShopName},";
                    subject += $"{Details.ShopName}:{Details.ShopName}";
                    list.Add(Details);
                }

                decimal PyaPreferentia = 0;
                ///优惠券计算目前支持一张优惠券
                if (Input.ShopUserCouponId != null)
                {
                    foreach (var item in Input.ShopUserCouponId)
                    {
                        ///优惠券使用生成
                        var shopCoupon = _shopUserCouponManager.UserShopUserCoupon(item, model.OrderNumber);
                        ShopOrderCoupon shopOrderCoupon = new ShopOrderCoupon();
                        shopOrderCoupon.OrderNumber = model.OrderNumber;
                        shopOrderCoupon.OrderId = model.Id;
                        shopOrderCoupon.ShopCouponId = shopCoupon.ShopCouponId;
                        shopOrderCoupon.ShopUserCouponId = shopCoupon.Id;
                        PyaPreferentia += shopCoupon.ShopCoupon.CouponPrice;
                        await _shopOrderCouponManager.CreateShopOrderCoupon(shopOrderCoupon);
                        ///如果优惠券存在
                        CreateCouponMethod(shopCoupon, list);

                    }
                }

                foreach (var item in list)
                {
                    await _shopOrderDetailsManager.CreateShopOrderDetails(item);
                }
                model.PayTotal = list.Sum(o => o.PayTotalPrice);//总的应支付金额
                model.PyaPreferentia = PyaPreferentia;
                model.PayAmount = (model.PayTotal - model.PyaPreferentia) <= 0 ? 0 : (model.PayTotal - model.PyaPreferentia);
                if (model.PayAmount == 0)
                    new UserFriendlyException("订单金额异常");

                await _shopOrderManager.CreateShopOrder(model);
            }
            #endregion

            string apyStr = string.Empty;
            var m = new PayData
            {
                OrderNumber = model.OrderNumber,
                PayTotal = model.PayAmount,
                Id = model.Id,
                Body = body.Length >= 128 ? body.Substring(0, 128) : body,
                Subject = subject.Length >= 256 ? subject.Substring(0, 256) : subject,
               
            };

            if (model.PayType == PayType.支付宝支付)
            {
                m.CallBackNotify_url = _appConfiguration["PayCallBackURL:Alipay"];
            }
            if (model.PayType == PayType.微信支付)
            {
                m.CallBackNotify_url = _appConfiguration["PayCallBackURL:WeiXin"];
            }
            apyStr = _payPayAppService.PayString(m, model.PayType);
            return apyStr;
        }





        /// <summary>
        /// 优惠券计算对象
        /// </summary>
        /// <param name="couponOrderModel"></param>
        /// <param name="enterOrderDetails"></param>

        private static void CreateCouponMethod(ShopUserCoupon couponOrderModel, List<ShopOrderDetails> enterOrderDetails)
        {

            var couponModel = couponOrderModel;
            if (couponModel != null)
            {
                NumberFormatInfo provider = new NumberFormatInfo();
                provider.CurrencyDecimalDigits = 2;
                provider.NumberDecimalDigits = 2;
                ///如果是全品类通用
                if (couponModel.ShopCoupon.CouponType == CouponType.All && (couponModel.ShopCoupon.UseCoupon == UseCoupon.FullReduction || couponModel.ShopCoupon.UseCoupon == UseCoupon.Universal))
                {
                    //
                    var ToaltPrice = enterOrderDetails.Sum(o => o.PayTotalPrice);
                    var p =Convert.ToDecimal(couponModel.ShopCoupon.CouponPrice / ToaltPrice, provider);
                    enterOrderDetails.ForEach(o =>
                    {
                        var pay = Convert.ToDecimal((o.PayTotalPrice * p), provider);//优惠金额
                        o.PayPrice = decimal.Round(Convert.ToDecimal((o.PayTotalPrice - pay) / o.ProductCount, provider), 2, MidpointRounding.ToEven);//优惠后的单价
                        o.PayPrice = o.PayPrice <= 0 ? 0 : o.PayPrice;
                        o.DiscountPrice = pay;
                        o.PayAmountPrice = (o.PayTotalPrice - o.DiscountPrice) <= 0 ? 0 : decimal.Round((o.PayTotalPrice - o.DiscountPrice),2);//实际应该支付金额

                    });


                }

                if (couponModel.ShopCoupon.CouponType == CouponType.Single && (couponModel.ShopCoupon.UseCoupon == UseCoupon.FullReduction || couponModel.ShopCoupon.UseCoupon == UseCoupon.Universal))
                {
                    //
                    var ToaltPrice = enterOrderDetails.Where(o => o.ShopTypeid == couponModel.ShopCoupon.ProductTypeId).Sum(o => o.PayTotalPrice);

                    var p =Convert.ToDecimal(couponModel.ShopCoupon.CouponPrice / ToaltPrice, provider);

                    enterOrderDetails.ForEach(o =>
                        {
                            if (o.ShopTypeid == couponModel.ShopCoupon.ProductTypeId)
                            {
                                var pay =Convert.ToDecimal((o.PayTotalPrice * p), provider);//优惠金额
                                o.PayPrice = decimal.Round(Convert.ToDecimal((o.PayTotalPrice - pay) / o.ProductCount, provider), 2, MidpointRounding.ToEven);//优惠后的单价
                                o.PayPrice = o.PayPrice <= 0 ? 0 : o.PayPrice;
                                o.DiscountPrice = pay;
                                o.PayAmountPrice = (o.PayTotalPrice - o.DiscountPrice) <= 0 ? 0 : decimal.Round((o.PayTotalPrice - o.DiscountPrice), 2);//实际应该支付金额
                            }

                        });

                }
            }
        }


        private  void EnterOrderBySkillBuy(Guid productId,int count) {
           var model= _shopSecondkillRepository.GetAll().Where(o => o.ShopProductId == productId && o.SecondkillBeginTime<=DateTime.Now && o.SecondkillEndTime>=DateTime.Now).FirstOrDefault();
            if (model != null)
            {
                if(count>model.SecondkillSingleCount)
                 throw   new UserFriendlyException("秒杀商品的数量超出本次最大购买数");

                //查看是否存在秒杀购买的订单信息
                var list= _shopOrderDetailsRepository.GetAll().Where(o => o.UserId == AbpSession.UserId.Value && o.ShopproductId == productId && o.CreationTime >= model.SecondkillBeginTime && o.CreationTime <= model.SecondkillEndTime);
                if (list.Count() > 0)
                {
                    if (model.SecondkillSingleCount < (list.Sum(o => o.ProductCount)+count))
                        throw  new UserFriendlyException("秒杀商品的数量超出本次最大购买数");
                }
            }

        }

        #endregion

        #region 订单列表查询
        /// <summary>
        /// app获取订单状态列表
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="pagesize">每页显示调试</param>
        /// <param name="payStatus">支付状态</param>
        /// <param name="DeliveryStatus">发货状态</param>
        /// <param name="EvaluateStatus">评论状态</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task<IPagedList<ShopOrderAppDto>> GetOrderStatus(int page, int pagesize, PayStatus? payStatus, DeliveryStatus? DeliveryStatus, EvaluateStatus? EvaluateStatus, string keywords = "")
        {
            var userid = AbpSession.UserId;
            if (!userid.HasValue)
                throw new UserFriendlyException(120, "请先登陆！");


            var orderList = _shopOrderRepository.GetAll().Where(o => o.UserId == userid);

            if (DeliveryStatus != null)
            {
                orderList = orderList.Where(o => o.PayStatus == PayStatus.已支付 && o.DeliveryStatus == DeliveryStatus);
            }
            else
            {
                if (payStatus != null)
                    orderList = orderList.Where(o => o.PayStatus == payStatus);
            }

            IPagedList<ShopOrderAppDto> model;
            if (EvaluateStatus == null)
            {
                var query = orderList.ProjectTo<ShopOrderAppDto>().GroupJoin(_shopOrderDetailsRepository.GetAll(), o => o.Id, t => t.OrderId, (o, t) => new ShopOrderAppDto
                {
                    Id = o.Id,
                    UserId = o.UserId,
                    OrderNumber = o.OrderNumber,
                    PayStatus = o.PayStatus,
                    PayType = o.PayType,
                    DeliveryStatus = o.DeliveryStatus,
                    PayTotal = o.PayTotal,
                    PyaPreferentia = o.PyaPreferentia,
                    PayAmount = o.PayAmount,
                    ReceivingAddress = o.ReceivingAddress,
                    ActualReceivingName = o.ActualReceivingName,
                    ActualReceivingTel = o.ActualReceivingTel,
                    ActualReceivingAddress = o.ActualReceivingAddress,
                    PayTime = o.PayTime,
                    OrderLeavingMessage = o.OrderLeavingMessage,
                    ShopOrderAppDetailsDto = t.MapTo<List<ShopOrderAppDetailsDto>>(),
                    CreatorUserId = o.CreatorUserId,
                    CreationTime = o.CreationTime
                });

                if (!string.IsNullOrEmpty(keywords))
                    query = query.Where(o => o.ShopOrderAppDetailsDto.Where(d => d.ShopName.Contains(keywords)).Any());

                model = await query.OrderByDescending(o => o.CreationTime).ToPagedListAsync(page, pagesize);
            }
            else
            {
                model = await GetOrderEvaluateStatus(page, pagesize, keywords);
            }

            return model;
        }








        /// <summary>
        ///App 获取订单未评价的商品信息
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public async Task<IPagedList<ShopOrderAppDto>> GetOrderEvaluateStatus(int page, int pagesize, string keywords)
        {

            var orderList = _shopOrderRepository.GetAll().Where(o => o.PayStatus == PayStatus.已支付 && o.DeliveryStatus == DeliveryStatus.已确认 && o.UserId == AbpSession.UserId.Value);
            var query = orderList.ProjectTo<ShopOrderAppDto>().GroupJoin(_shopOrderDetailsRepository.GetAll(), o => o.Id, t => t.OrderId, (o, t) => new ShopOrderAppDto
            {
                Id = o.Id,
                UserId = o.UserId,
                OrderNumber = o.OrderNumber,
                PayStatus = o.PayStatus,
                PayType = o.PayType,
                DeliveryStatus = o.DeliveryStatus,
                PayTotal = o.PayTotal,
                PyaPreferentia = o.PyaPreferentia,
                PayAmount = o.PayAmount,
                ReceivingAddress = o.ReceivingAddress,
                ActualReceivingName = o.ActualReceivingName,
                ActualReceivingTel = o.ActualReceivingTel,
                ActualReceivingAddress = o.ActualReceivingAddress,
                PayTime = o.PayTime,
                OrderLeavingMessage = o.OrderLeavingMessage,
                ShopOrderAppDetailsDto = t.MapTo<List<ShopOrderAppDetailsDto>>(),
                CreationTime = o.CreationTime
            }).Where(o => o.ShopOrderAppDetailsDto.Where(t => t.EvaluateStatus == EvaluateStatus.未评价).Any());
            if (!string.IsNullOrEmpty(keywords))
                query = query.Where(o => o.ShopOrderAppDetailsDto.Where(d => d.ShopName.Contains(keywords)).Any());

            var model = await query.OrderByDescending(o => o.CreationTime).ToPagedListAsync(page, pagesize);

            return model;
        }

        #endregion

        /// <summary>
        /// 得到订单详细
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public ShopOrderAppDto GetOrderByIdDetails(Guid orderId)
        {

            var orderList = _shopOrderRepository.GetAll().Where(o => o.Id == orderId);
            return orderList.ProjectTo<ShopOrderAppDto>().GroupJoin(_shopOrderDetailsRepository.GetAll(), o => o.Id, t => t.OrderId, (o, t) => new ShopOrderAppDto
            {
                Id = o.Id,
                UserId = o.UserId,
                OrderNumber = o.OrderNumber,
                PayStatus = o.PayStatus,
                PayType = o.PayType,
                DeliveryStatus = o.DeliveryStatus,
                PayTotal = o.PayTotal,
                PyaPreferentia = o.PyaPreferentia,
                PayAmount = o.PayAmount,
                ReceivingAddress = o.ReceivingAddress,
                ActualReceivingName = o.ActualReceivingName,
                ActualReceivingTel = o.ActualReceivingTel,
                ActualReceivingAddress = o.ActualReceivingAddress,
                PayTime = o.PayTime,
                OrderLeavingMessage = o.OrderLeavingMessage,
                ShopOrderAppDetailsDto = t.MapTo<List<ShopOrderAppDetailsDto>>(),
                CreatorUserId = o.CreatorUserId,
                CreationTime = o.CreationTime
            }).FirstOrDefault();

        }
        /// <summary>
        /// App-订单收货
        /// </summary>
        /// <param name="id">订单Id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task OrderReceiptAppAsync(Guid id)
        {
            var order = _shopOrderRepository.GetAll().Where(o => o.Id == id).First();
            order.DeliveryStatus = DeliveryStatus.已确认;
            await _shopOrderRepository.UpdateAsync(order);
            var detils = _shopOrderDetailsRepository.GetAll().Where(o => o.OrderId == id);
            foreach (var item in detils)
            {
                if (item.DeliveryStatus == DeliveryStatus.已发货)
                    item.DeliveryStatus = DeliveryStatus.已确认;

                await _shopOrderDetailsRepository.UpdateAsync(item);
            }
            ///通知管理人员
            OrderOperationNotificationData orderOperationNotificationData = new OrderOperationNotificationData(NotificationType.物流收货, NotificationMessage.OrderDeliverySuccess, id.ToString(), null);

            await _publishNotifications.Publish_OrderOperation(orderOperationNotificationData);

        }


        /// <summary>
        /// App-订单删除
        /// </summary>
        /// <param name="id">订单Id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task OrderDeteleAsync(Guid id)
        {
            var order = await _shopOrderRepository.GetAsync(id);
            if (order.PayStatus != PayStatus.取消订单)
                throw new UserFriendlyException(2, "只有已取消的订单允许删除！");
            await _shopOrderRepository.DeleteAsync(order);
        }


        /// <summary>
        /// 修改支付方式
        /// </summary>
        /// <param name="Id">订单id</param>
        /// <param name="payType">支付类别 0支付宝1微信</param>
        /// <returns></returns>

        public async Task<string> ModifyPayType(Guid Id, PayType payType)
        {

            var model = await _shopOrderRepository.GetAsync(Id);
            model.PayType = payType;
            string apyStr = string.Empty;

            var m = new PayData
            {
                OrderNumber = model.OrderNumber,
                PayTotal = model.PayAmount,
                Id = model.Id,
                Body = "商品支付",
                Subject = "饭碗易购商品支付"
            };
            if (model.PayType == PayType.支付宝支付)
            {
                m.CallBackNotify_url = _appConfiguration["PayCallBackURL:Alipay"];
            }
            if (model.PayType == PayType.微信支付)
            {
                m.CallBackNotify_url = _appConfiguration["PayCallBackURL:WeiXin"];
            }
            apyStr = _payPayAppService.PayString(m, model.PayType);
            return apyStr;
        }

        /// <summary>
        /// 根据订单编号换取支付凭证
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<string> GetPayDoing(Guid Id)
        {

            var model = await _shopOrderRepository.GetAsync(Id);
            string apyStr = string.Empty;
            if (model != null && model.PayStatus == PayStatus.未支付)
            {
                var m = new PayData
                {
                    OrderNumber = model.OrderNumber,
                    PayTotal = model.PayAmount,
                    Id = model.Id,
                    Body = "商品支付",
                    Subject = "饭碗易购商品支付"
                 
                };
                if (model.PayType == PayType.支付宝支付)
                {
                    m.CallBackNotify_url = _appConfiguration["PayCallBackURL:Alipay"];
                }
                if (model.PayType == PayType.微信支付)
                {
                    m.CallBackNotify_url = _appConfiguration["PayCallBackURL:WeiXin"];
                }
                apyStr = _payPayAppService.PayString(m, model.PayType);
            }
            else
            {
                new UserFriendlyException("该订单不可支付");
            }
            return apyStr;
        }

        /// <summary>
        /// 求当前商品价格
        /// </summary>
        /// <param name="shopSkuId"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        private decimal ShopPrice(Guid shopSkuId, Guid Id)
        {

            var shopProduct = _shopProductRepository.Get(Id);
            decimal m = shopProduct.SpcemarketPrice;
            if (shopSkuId != Guid.Empty && shopProduct.SpceIsActive == true)
            {
                var model = _shopProductSkuRepository.Get(shopSkuId);
                m = model.SpceMarketPrice;
            }
            return m;
        }

        #region 确认订单服务
        /// <summary>
        /// 立即购买确认订单
        /// </summary>
        /// <param name="carId">购物车id</param>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<EnterOrderModel> EnterOrder(OrderModelInput model)
        {

            EnterOrderModel enterOrderModel = new EnterOrderModel();
            try
            {
                if (AbpSession.UserId.HasValue)
                {
                    enterOrderModel.ShopReceivingAddressDto = _shopReceivingAddressAppService.GetShopReceivingAddressByIsDefalut();
                    List<EnterOrderDetails> enterOrderDetails = new List<EnterOrderDetails>();
                    if (model != null && model.Id != Guid.Empty)
                    {
                        enterOrderDetails = _shopProductRepository.GetAll().Where(o => o.Id == model.Id && o.IsGrounding == true).Select(n => new EnterOrderDetails
                        {
                            Id = n.Id,
                            ShopTypeid = n.ShopTypeid,
                            ImagePic = n.ImagePic,
                            ProductName = n.ProductName,
                            ProductNumber = n.ProductName,
                            ProductDetails = n.ProductDetails,
                            MarketPrice = n.MarketPrice,
                            Unit = n.Unit,
                            SpceWeight = n.SpceWeight,
                            ProductPayCount = model.ProductCount,
                            SkuId = model.ShopSkuId
                        }).ToList();

                        enterOrderDetails.ForEach(o =>
                        {
                            o.SpcemarketPrice = ShopPrice(o.SkuId, o.Id);
                            o.PayPrice = o.SpcemarketPrice * o.ProductPayCount;
                            o.SkuName = _shopProductSkuRepository.Get(o.SkuId).SpaceValueName;
                        });
                    }
                    enterOrderModel.ShopUserCouponDto = await _shopUserCouponAppService.GetSelfAvailableCouponPageList(1, 20, enterOrderDetails.GroupBy(o => o.ShopTypeid).Select(o => new OrderShopUserCoupon { ShopTypeId = o.Key, Total = o.Sum(s => s.PayPrice) }).ToList());
                    if (model.couPonId != null)
                        NewMethod(model.couPonId, enterOrderModel, enterOrderDetails);


                    ///得到总的钱
                    enterOrderModel.ProductPayCountNumber = enterOrderDetails.Sum(o => o.ProductPayCount);
                    enterOrderModel.ToaltPrice = enterOrderDetails.Sum(o => o.PayPrice);
                    ///获取可用优惠券

                    enterOrderModel.EnterOrderDetails = enterOrderDetails;
                }

            }
            catch (Exception exe)
            {

                throw new UserFriendlyException("系统繁忙", exe);
            }
         

            return enterOrderModel;
        }
        #region 确认订单计算符合使用的优惠券
        private static void NewMethod(Guid? couPonId, EnterOrderModel enterOrderModel, List<EnterOrderDetails> enterOrderDetails)
        {
            if (couPonId != null)
            {
                var couponModel = enterOrderModel.ShopUserCouponDto.Where(o => o.Id == couPonId).FirstOrDefault();
                if (couponModel != null)
                {
                    NumberFormatInfo provider = new NumberFormatInfo();
                    provider.CurrencyDecimalDigits = 2;
                    provider.NumberDecimalDigits = 2;
                    ///如果是全品类通用
                    if (couponModel.ShopCoupon.CouponType == CouponType.All && (couponModel.ShopCoupon.UseCoupon == UseCoupon.FullReduction || couponModel.ShopCoupon.UseCoupon == UseCoupon.Universal))
                    {
                        //
                        var ToaltPrice = enterOrderDetails.Sum(o => o.PayPrice);
                        var p = Convert.ToDecimal(couponModel.ShopCoupon.CouponPrice / ToaltPrice, provider);

                        enterOrderDetails.ForEach(o =>
                        {
                            var PayPrice = o.SpcemarketPrice * o.ProductPayCount;
                            var tempPrice =Convert.ToDecimal((PayPrice * p), provider);
                            //o.MarketPrice = o.SpcemarketPrice;
                            o.SpcemarketPrice = decimal.Round(Convert.ToDecimal((PayPrice - tempPrice) / o.ProductPayCount, provider), 2);
                            o.SpcemarketPrice = o.SpcemarketPrice <= 0 ? 0 : o.SpcemarketPrice;//原价
                            o.PayPrice = (PayPrice - tempPrice) <= 0 ? 0 : decimal.Round((PayPrice - tempPrice), 2);

                        });


                    }

                    if (couponModel.ShopCoupon.CouponType == CouponType.Single && (couponModel.ShopCoupon.UseCoupon == UseCoupon.FullReduction || couponModel.ShopCoupon.UseCoupon == UseCoupon.Universal))
                    {
                        //
                        var ToaltPrice = enterOrderDetails.Where(o => o.ShopTypeid == couponModel.ShopCoupon.ProductTypeId).Sum(o => o.PayPrice);
                        //求出占比
                        var p = Convert.ToDecimal(couponModel.ShopCoupon.CouponPrice / ToaltPrice, provider);
                        enterOrderDetails.ForEach(o =>
                        {
                            if (o.ShopTypeid == couponModel.ShopCoupon.ProductTypeId)
                            {
                                var PayPrice = o.SpcemarketPrice * o.ProductPayCount;
                                //根据赞比求出平均值
                                var tempPrice = Convert.ToDecimal((PayPrice * p), provider);
                                /// o.MarketPrice = o.SpcemarketPrice;
                                //根据计算出来价格除总数
                                o.SpcemarketPrice = decimal.Round(Convert.ToDecimal((PayPrice - tempPrice) / o.ProductPayCount, provider), 2);
                                o.SpcemarketPrice = o.SpcemarketPrice <= 0 ? 0 : o.SpcemarketPrice;
                                o.PayPrice = (PayPrice - tempPrice) <= 0 ? 0 : decimal.Round((PayPrice - tempPrice), 2);
                            }

                        });


                    }
                }
            }
        }
        #endregion


        /// <summary>
        /// 购物车订单确认
        /// </summary>
        /// <param name="carId">购物车id</param>
        /// <param name="model"></param>
        /// <returns></returns>

        public async Task<EnterOrderModel> EnterCarOrder(GuidModel carId)
        {

            EnterOrderModel enterOrderModel = new EnterOrderModel();
            if (AbpSession.UserId.HasValue)
            {
                enterOrderModel.ShopReceivingAddressDto = _shopReceivingAddressAppService.GetShopReceivingAddressByIsDefalut();
                List<EnterOrderDetails> enterOrderDetails = new List<EnterOrderDetails>();
                if (carId.CarId.Count > 0 && carId.CarId != null)
                {
                    var ids = carId.CarId.Select(o => o.Id).ToArray();
                    enterOrderDetails = _shopCarrepository.GetAll().Where(o => ids.Any(s => s == o.Id && o.UserId == AbpSession.UserId.Value)).Join(_shopProductRepository.GetAll().Where(o => o.IsGrounding == true), o => o.ShopproductId, n => n.Id, (o, n) => new EnterOrderDetails
                    {
                        Id = n.Id,
                        ShopTypeid = n.ShopTypeid,
                        ImagePic = n.ImagePic,
                        ProductName = n.ProductName,
                        ProductNumber = n.ProductName,
                        ProductDetails = n.ProductDetails,
                        Unit = n.Unit,
                        MarketPrice = n.MarketPrice,
                        SpceWeight = n.SpceWeight,
                        ProductPayCount = o.ProductCount,
                        SkuId = o.ShopSkuId
                    }).ToList();
                    enterOrderDetails.ForEach(o =>
                    {
                        o.SpcemarketPrice = ShopPrice(o.SkuId, o.Id);
                        o.PayPrice = o.SpcemarketPrice * o.ProductPayCount;
                        o.SkuName = _shopProductSkuRepository.Get(o.SkuId).SpaceValueName;
                    });
                }

                enterOrderModel.ShopUserCouponDto = await _shopUserCouponAppService.GetSelfAvailableCouponPageList(1, 20, enterOrderDetails.GroupBy(o => o.ShopTypeid).Select(o => new OrderShopUserCoupon { ShopTypeId = o.Key, Total = o.Sum(s => s.PayPrice) }).ToList());
                if (carId.couPonId != null)
                    NewMethod(carId.couPonId, enterOrderModel, enterOrderDetails);
                ///得到总的钱
                enterOrderModel.ProductPayCountNumber = enterOrderDetails.Sum(o => o.ProductPayCount);
                enterOrderModel.ToaltPrice = enterOrderDetails.Sum(o => o.PayPrice);
                ///获取可用优惠券
                enterOrderModel.EnterOrderDetails = enterOrderDetails;
            }


            return enterOrderModel;
        }

        #endregion
        /// <summary>
        /// 获取订单明细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<List<ShopOrderDetailsOutputDto>> GetOrderDetailsByOrderId(Guid id)
        {
            return await _shopOrderDetailsRepository.GetAll().Where(o => o.OrderId == id).ProjectTo<ShopOrderDetailsOutputDto>().ToListAsync();

        }





        #region 后台管理
        /// <summary>
        /// 后台管理-获取订单列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public async Task<LayerDataBaseDto> GetShopOrderLayerDataAsync(int page, int limit, ShopOrderFilter filter)
        {
            var query = _shopOrderRepository.GetAll().GroupJoin(_shopOrderDetailsRepository.GetAll(), i => i.Id, j => j.OrderId, (i, j) => new
            {
                i.Id,
                i.OrderNumber,
                i.CreationTime,
                i.PayTotal,
                i.PayAmount,
                i.PayStatus,
                i.PayType,
                i.DeliveryStatus,
                i.ReceivingAddress,
                OrderDetails = j
            }).Join(_repositoryShopReceivingAddress.GetAll(), i => i.ReceivingAddress, j => j.Id, (i, j) => new
            {
                i.Id,
                i.OrderNumber,
                i.CreationTime,
                i.PayTotal,
                i.PayAmount,
                i.PayStatus,
                i.PayType,
                i.DeliveryStatus,
                j.ReceivingName,
                j.ReceivingTel,
                j.ReceivingAddress,
                i.OrderDetails
            });
            if (filter != null)
            {
                //订单状态
                if (filter.ShopOrderStatus.HasValue)
                {
                    switch (filter.ShopOrderStatus)
                    {
                        case ShopOrderStatus.SettleAccounts://待结算的订单明细存在就属于待结算订单
                            query = query.Where(o => o.OrderDetails.Where(i => i.SettlementStatus == SettlementStatus.未结算).Any());
                            break;
                        case ShopOrderStatus.Ship://待发货的订单明细存在就属于待发货订单
                            query = query.Where(o => o.OrderDetails.Where(i => i.DeliveryStatus == DeliveryStatus.未发货).Any() && o.PayStatus == PayStatus.已支付);
                            break;
                        case ShopOrderStatus.Receipt://待收货的订单明细存在就属于待收货订单
                            query = query.Where(o => o.OrderDetails.Where(i => i.DeliveryStatus == DeliveryStatus.已发货).Any());
                            break;
                        default:
                            break;
                    }
                }

                if (!string.IsNullOrEmpty(filter.keyword))//订单关键词
                    query = query.Where(o => o.OrderNumber.Contains(filter.keyword));

                if (filter.DeliveryStatus.HasValue)//收货状态
                    query = query.Where(o => o.DeliveryStatus == filter.DeliveryStatus.Value);

                if (filter.PayStatus.HasValue)//支付状态
                    query = query.Where(o => o.PayStatus == filter.PayStatus.Value);

                if (!string.IsNullOrEmpty(filter.CreationTime))//创建时间
                {
                    DateTime beginTime = new DateTime();
                    DateTime endTime = new DateTime();
                    var timerange = filter.CreationTime.Split('~');
                    if (timerange.Count() == 2)
                    {
                        beginTime = Convert.ToDateTime(timerange[0].Trim());
                        endTime = Convert.ToDateTime(timerange[1].Trim());
                    }

                    query = query.Where(o => o.CreationTime >= beginTime && o.CreationTime <= endTime.AddHours(24));
                }

            }

            var pagelist = await query.OrderByDescending(o => o.CreationTime).Select(o => new ShopOrderOutputDto
            {
                Id = o.Id,
                ShopReceivingAddress = new ShopAppReceivingAddressDto
                {
                    ReceivingAddress = o.ReceivingAddress,
                    ReceivingName = o.ReceivingName,
                    ReceivingTel = o.ReceivingTel,
                },
                CreationTime = o.CreationTime,
                OrderNumber = o.OrderNumber,
                PayAmount = o.PayAmount,
                PayStatus = o.PayStatus,
                PayTotal = o.PayTotal,
                PayType = o.PayType,
                DeliveryStatus = o.DeliveryStatus,
            }).ToPagedListAsync(page, limit);

            LayerDataBaseDto dto = new LayerDataBaseDto();
            dto.Data = pagelist;
            dto.Count = pagelist.TotalItemCount;
            return dto;

        }
        /// <summary>
        /// 获取前5条待发货订单
        /// </summary>
        public async Task<LayerDataBaseDto> GetStayOrders()
        {
            var query = _shopOrderRepository.GetAll().GroupJoin(_shopOrderDetailsRepository.GetAll(), i => i.Id, j => j.OrderId, (i, j) => new
            {
                i.Id,
                i.OrderNumber,
                i.CreationTime,
                i.PayTotal,
                i.PayAmount,
                i.PayStatus,
                i.PayType,
                i.DeliveryStatus,
                i.ReceivingAddress,
                OrderDetails = j

            }).Join(_repositoryShopReceivingAddress.GetAll(), i => i.ReceivingAddress, j => j.Id, (i, j) => new
            {
                i.Id,
                i.OrderNumber,
                i.CreationTime,
                i.PayTotal,
                i.PayAmount,
                i.PayStatus,
                i.PayType,
                i.DeliveryStatus,
                j.ReceivingName,
                j.ReceivingTel,
                j.ReceivingAddress,
                i.OrderDetails
            });

            query = query.Where(o => o.OrderDetails.Where(i => i.DeliveryStatus == DeliveryStatus.未发货).Any() && o.PayStatus == PayStatus.已支付);

            var pagelist = await query.Select(o => new ShopOrderOutputDto
            {
                Id = o.Id,
                ShopReceivingAddress = new ShopAppReceivingAddressDto
                {
                    ReceivingAddress = o.ReceivingAddress,
                    ReceivingName = o.ReceivingName,
                    ReceivingTel = o.ReceivingTel,
                },
                CreationTime = o.CreationTime,
                OrderNumber = o.OrderNumber,
                PayAmount = o.PayAmount,
                PayStatus = o.PayStatus,
                PayTotal = o.PayTotal,
                PayType = o.PayType,
                DeliveryStatus = o.DeliveryStatus,
            }).OrderBy(o => o.CreationTime).Take(5).ToListAsync();

            LayerDataBaseDto dto = new LayerDataBaseDto();
            dto.Data = pagelist;

            return dto;

        }

        /// <summary>
        /// 后台管理-获取订单处理数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ShopOrderHandleDto> GetShopOrderHandleDtoByOrderId(Guid id)
        {
            var query = _shopOrderRepository.GetAllIncluding(o => o.ShopReceivingAddress).Where(o => o.Id == id).GroupJoin(_shopOrderDetailsRepository.GetAll(), i => i.Id, j => j.OrderId, (i, j) => new
            {
                ShopOrder = i,
                Details = j.Join(_shopProductRepository.GetAll(), x => x.ShopproductId, y => y.Id, (x, y) => new ShopOrderDetailsOutputDto { Id = x.Id, DeliveryStatus = x.DeliveryStatus, DeliveryTime = x.DeliveryTime, EvaluateStatus = x.EvaluateStatus, PayPrice = x.PayPrice, PriceDifference = x.PriceDifference, ProductCount = x.ProductCount, Returngoods = x.Returngoods, SettlementStatus = x.SettlementStatus, ShopName = y.ProductName }).ToList(),
                UserId = i.UserId
            });

            var entity = query.Select(o => new ShopOrderHandleDto { Id = o.ShopOrder.Id, ShopOrderDetails = o.Details, ShopOrderInformation = o.ShopOrder.MapTo<ShopAppOrderInformationDto>() }).FirstOrDefault();

            if (entity == null)
            {
                return new ShopOrderHandleDto();
            }

            entity.ShopUser = (await _repositoryUser.GetAsync(entity.ShopOrderInformation.UserId)).MapTo<ShopAppUserDto>();


            return entity;

        }

        public async Task<ShopOrderHandleDto> GetShopOrderHandleDtoByOrderNumber(string orderNumber)
        {
            var query = _shopOrderRepository.GetAllIncluding(o => o.ShopReceivingAddress).Where(o => o.OrderNumber == orderNumber).GroupJoin(_shopOrderDetailsRepository.GetAll(), i => i.Id, j => j.OrderId, (i, j) => new
            {
                ShopOrder = i,
                Details = j.Join(_shopProductRepository.GetAll(), x => x.ShopproductId, y => y.Id, (x, y) => new ShopOrderDetailsOutputDto { Id = x.Id, DeliveryStatus = x.DeliveryStatus, DeliveryTime = x.DeliveryTime, EvaluateStatus = x.EvaluateStatus, PayPrice = x.PayPrice, PriceDifference = x.PriceDifference, ProductCount = x.ProductCount, Returngoods = x.Returngoods, SettlementStatus = x.SettlementStatus, ShopName = y.ProductName }).ToList(),
                UserId = i.UserId
            });

            var entity = query.Select(o => new ShopOrderHandleDto { Id = o.ShopOrder.Id, ShopOrderDetails = o.Details, ShopOrderInformation = o.ShopOrder.MapTo<ShopAppOrderInformationDto>() }).FirstOrDefault();

            if (entity == null)
            {
                return new ShopOrderHandleDto();
            }

            entity.ShopUser = (await _repositoryUser.GetAsync(entity.ShopOrderInformation.UserId)).MapTo<ShopAppUserDto>();
            return entity;

        }

        /// <summary>
        /// 后台管理-根据订单Id获取相应状态的订单明细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<LayerDataBaseDto> GetOrderDetailsByOrderIdAsync(Guid id, ShopOrderStatus status)
        {
            var query = _shopOrderDetailsRepository.GetAll().Where(o => o.OrderId == id);

            switch (status)
            {
                case ShopOrderStatus.SettleAccounts:
                    query = query.Where(o => o.SettlementStatus == SettlementStatus.未结算);
                    break;
                case ShopOrderStatus.Ship:
                    query = query.Where(o => o.DeliveryStatus == DeliveryStatus.未发货);
                    break;
                case ShopOrderStatus.Receipt:
                    query = query.Where(o => o.DeliveryStatus == DeliveryStatus.已发货);
                    break;
                case ShopOrderStatus.AfterSale:
                    query = query.Where(o => o.Returngoods == Returngoods.未退货 && o.DeliveryStatus == DeliveryStatus.已确认);
                    break;
                default:
                    break;
            }

            var list = await query.OrderByDescending(o => o.CreationTime).ProjectTo<ShopOrderDetailsDto>().ToListAsync();

            LayerDataBaseDto dto = new LayerDataBaseDto();
            dto.Data = list;

            return dto;
        }

        /// <summary>
        /// 订单发货
        /// </summary>
        /// <param name="ids">订单明细Id</param>
        /// <returns></returns>
        public async Task OrderShipAsync(List<Guid> ids)
        {
            foreach (var item in ids)
            {
                if (item != Guid.Empty)
                {


                    var detail = await _shopOrderDetailsRepository.GetAsync(item);
                    var orderModel = _shopOrderRepository.Get(detail.OrderId.Value);
                    if (orderModel.PayStatus != PayStatus.已支付)
                        throw new UserFriendlyException(2, "只有已支付的订单才能发货！");

                    if (orderModel.DeliveryStatus != DeliveryStatus.已发货)
                    {

                        orderModel.DeliveryStatus = DeliveryStatus.已发货;
                        await _shopOrderRepository.UpdateAsync(orderModel);
                    }



                    if (detail.DeliveryStatus == DeliveryStatus.未发货)
                    {
                        detail.DeliveryStatus = DeliveryStatus.已发货;
                        detail.DeliveryTime = DateTime.Now;


#if DEBUG
                        //发起确认收货延迟事件
                        await _backgroundJobManager.EnqueueAsync<ShopShipBackground, BasArg>(new BasArg { Id = item }, BackgroundJobPriority.Normal, TimeSpan.FromMinutes(2));
#else
  await _backgroundJobManager.EnqueueAsync<ShopShipBackground, BasArg>(new BasArg { Id = item }, BackgroundJobPriority.Normal, TimeSpan.FromDays(7));
#endif
                        ///发货修改
                        var shopappcatcheventDate = new RemoteEventData(RemoteTypeHelp.TYPEORDERDETAILSDELIVERYSTATUS)
                        {
                            Data = { [RemoteTypeHelp.MODELID] = detail.Id, [RemoteTypeHelp.MODELNAME] = nameof(ShopOrderDetails) }
                        };
                        remoteEventBus.Publish(RemoteTypeHelp.TOPICAPPORDERDETAILS, shopappcatcheventDate);

                    }
                    await _shopOrderDetailsRepository.UpdateAsync(detail);
                }
            }
        }

        /// <summary>
        /// 订单确认
        /// </summary>
        /// <param name="ids">订单明细Id</param>
        /// <returns></returns>
        public async Task OrderReceiptAsync(List<Guid> ids)
        {
            foreach (var item in ids)
            {
                if (item != Guid.Empty)
                {
                    var detail = await _shopOrderDetailsRepository.GetAsync(item);
                    if (detail.DeliveryStatus == DeliveryStatus.已发货)
                        detail.DeliveryStatus = DeliveryStatus.已确认;

                    await _shopOrderDetailsRepository.UpdateAsync(detail);
                }
            }
        }

        /// <summary>
        /// 订单申请售后
        /// </summary>
        /// <param name="ids">订单明细Id</param>
        /// <returns></returns>
        public async Task OrderAfterSaleAsync(List<Guid> ids)
        {
            foreach (var item in ids)
            {
                if (item != Guid.Empty)
                {
                    var detail = await _shopOrderDetailsRepository.GetAsync(item);
                    if (detail.DeliveryStatus == DeliveryStatus.已确认 && detail.Returngoods == Returngoods.未退货)
                        detail.Returngoods = Returngoods.售后申请;

                    await _shopOrderDetailsRepository.UpdateAsync(detail);
                }
            }
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="id">订单Id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task OrderCancelAsync(Guid id)
        {
            var entity = await _shopOrderRepository.GetAsync(id);
            entity.PayStatus = PayStatus.取消订单;
            await _shopOrderRepository.UpdateAsync(entity);
        }

        public async Task<List<ShopOrderExportDto>> GetExportDataAsync(ShopOrderStatus? status, string keyword)
        {
            var query = _shopOrderRepository.GetAllIncluding(o => o.ShopReceivingAddress).GroupJoin(_shopOrderDetailsRepository.GetAll(), i => i.Id, j => j.OrderId, (i, j) => new ShopOrderExportDto
            {
                Id = i.Id,
                OrderNumber = i.OrderNumber,
                CreationTime = i.CreationTime,
                PayStatus = i.PayStatus,
                PayTotal = i.PayTotal,
                PayAmount = i.PayAmount,
                PayTime = i.PayTime,
                ReceivingName = i.ShopReceivingAddress.ReceivingName,
                ReceivingTel = i.ShopReceivingAddress.ReceivingTel,
                ReceivingAddress = i.ShopReceivingAddress.ReceivingAddress,
                ShopOrderDetils = j.Select(o => new ShopOrderDetilsExportDto
                {
                    ShopProductName = o.ShopName,
                    ProductCount = o.ProductCount,
                    PayPrice = o.PayPrice,
                    SkuName = o.SkuName,
                    Returngoods = o.Returngoods,
                    ReturngoodsPrice = o.ReturngoodsPrice,
                    refundNo = o.refundNo,
                    DeliveryStatus = o.DeliveryStatus,
                    DeliveryTime = o.DeliveryTime,
                    EvaluateStatus = o.EvaluateStatus,
                    SettlementStatus = o.SettlementStatus,
                    SettlementTime = o.SettlementTime,
                    PriceDifference = o.PriceDifference

                }).ToList()
            });

            switch (status)
            {
                case ShopOrderStatus.SettleAccounts://待结算的订单明细存在就属于待结算订单
                    query = query.Where(o => o.ShopOrderDetils.Where(i => i.SettlementStatus == SettlementStatus.未结算).Any());
                    break;
                case ShopOrderStatus.Ship://待发货的订单明细存在就属于待发货订单
                    query = query.Where(o => o.ShopOrderDetils.Where(i => i.DeliveryStatus == DeliveryStatus.未发货).Any());
                    break;
                case ShopOrderStatus.Receipt://待收货的订单明细存在就属于待收货订单
                    query = query.Where(o => o.ShopOrderDetils.Where(i => i.DeliveryStatus == DeliveryStatus.已发货).Any());
                    break;
                default:
                    break;
            }

            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(o => o.OrderNumber.Contains(keyword));

            return await query.ToListAsync();

        }
        #endregion
    }
}
